import React from 'react';
import { TreeData } from '../typings';
import file from '../assets/file.png';
import closedFolder from '../assets/closed-folder.png';
import openedFolder from '../assets/opened-folder.png';

interface Props {
    data: TreeData
    onCollapse:any
    onCheck: any
}

class TreeNode extends React.Component<Props> {
    constructor(props: Props) {
        super(props);
    }
    render() {
        let { data: { name, children,collapsed = false, key,checked = false } } = this.props;
        let caret = null;  //箭头
        let icon =null;  //文件图标
        if(children){
            if (children.length > 0) {
                caret = (
                    <span className={`collapse ${collapsed ? 'caret-right' : 'caret-down'}`}
                        onClick={() => this.props.onCollapse(key)}
                    />
                )
                icon = collapsed ? closedFolder : openedFolder;
            } else {
                caret = null;
                icon = file;
            }
        } else {
            caret = (
                <span className={`collapse caret-right`}
                    onClick={() => this.props.onCollapse(key)}
                />
            )
            icon = closedFolder;
        }

        
        return (
            // 整棵树
            <div className="tree-node">
                {/* 父亲 */}
                <div className="inner">
                    {caret}
                    <span className="content">
                        <input type="checkbox" checked={checked} onChange={() => this.props.onCheck(key)} />
                         <img style={{ width: 20 }} src={icon} />
                        {name}
                    </span>
                </div>
                {/* 儿子 孙子 重孙 */}
                {
                    (children && children.length > 0 && !collapsed) && (
                        <div className="children">
                            {
                                children.map((item: TreeData) => (
                                    <TreeNode onCollapse={this.props.onCollapse} key={item.key} data={item} 
                                    onCheck={this.props.onCheck}/>
                                ))
                            }
                        </div>
                    )
                }
            </div>
        )
    }
}
export default TreeNode;